package com.norns.torque.dialog

import android.content.Context
import android.os.Bundle
import android.os.IBinder
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.InputMethodManager
import android.widget.Toast
import com.hi.dhl.binding.viewbind
import com.norns.torque.databinding.DialogEditWifiBinding
import com.norns.torque.utils.AppContext

class EditWifiDialog :CommonDialog(){
    companion object{
        fun newInstance(wifiName:String,pwd:String):EditWifiDialog {
            val args = Bundle()
            args.putString("wifiName",wifiName)
            args.putString("pwd",pwd)
            val fragment = EditWifiDialog()
            fragment.arguments = args
            return fragment
        }
    }
    private val binding by viewbind<DialogEditWifiBinding>()
    private var btnClickListener:((wifi:String,pwd:String)->Unit)?=null

    fun setClickListener(listener:(wifi:String,pwd:String)->Unit){
        btnClickListener=listener
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        screenWidthAspect=0.9f
        return binding.root
    }
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        val wifiName=arguments?.getString("wifiName")?:""
        val pwd=arguments?.getString("pwd")?:""
        binding.editWiFiName.setText(wifiName)
        binding.editWiFiPwd.setText(pwd)

        binding.btnConfirm.setOnClickListener {
            val wifi= binding.editWiFiName.text?.toString()?:""
            val pwd= binding.editWiFiPwd.text?.toString()?:""
            if (wifi.isEmpty()||pwd.isEmpty()){
                Toast.makeText(AppContext.context,"wifi或密码不能为空",Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }
            btnClickListener?.invoke(wifi,pwd)
            dismiss()
        }

        binding.btnCancel.setOnClickListener {
            dismiss()
        }
    }

    override fun onDestroyView() {
        hideKeyboard(binding.editWiFiName.windowToken, AppContext.context)
        binding.editWiFiName.clearFocus()
        super.onDestroyView()
    }

    /**
     * 获取InputMethodManager，隐藏软键盘
     * @param token
     */
    private fun hideKeyboard(token: IBinder?, ct: Context) {
        if (token != null) {
            val im = ct.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
            im.hideSoftInputFromWindow(token, InputMethodManager.HIDE_NOT_ALWAYS)
        }
    }
}